package cc.magicjson.mybatis.mapper;

import cc.magicjson.entity.MyBatisUser;
import cc.magicjson.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    /**
     * 插入用户
     * 注意：这里不需要修改，因为插入操作不涉及结果集转换
     */
    @Insert("INSERT INTO users (name, email) VALUES (#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(MyBatisUser user);

    /**
     * 根据ID查找用户
     * 修改：移除了别名，让插件处理列名转换
     */
    @Select("SELECT id AS userId, name AS userName, email AS userEmail FROM users WHERE id = #{id}")
    User findById(Long id);

    /**
     * 查找所有用户
     * 注意：这里不需要修改，因为没有使用别名
     */
    @Select("SELECT * FROM users")
    List<User> findAll();

    /**
     * 更新用户
     * 注意：这里不需要修改，因为更新操作不涉及结果集转换
     */
    @Update("UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}")
    void update(MyBatisUser user);

    /**
     * 删除用户
     * 注意：这里不需要修改，因为删除操作不涉及结果集转换
     */
    @Delete("DELETE FROM users WHERE id = #{id}")
    void delete(Long id);

    /**
     * 根据ID查找用户，返回Map
     * 修改：移除了别名，让插件处理列名转换
     */
    @Select("SELECT id AS USER_ID, name AS userName, email AS USER_EMAIL FROM users WHERE id = #{id}")
    Map<String, Object> findByIdAsMap(Long id);

    /**
     * 复杂查询示例
     * 这个方法展示了如何处理复杂的查询，包括连接和自定义列名
     */
    @Select("SELECT u.id AS userId, u.name AS userName, u.email AS userEmail, " +
            "a.street AS addressStreet, a.city AS addressCity, a.country AS addressCountry " +
            "FROM users u " +
            "LEFT JOIN addresses a ON u.id = a.user_id " +
            "WHERE u.id = #{id}")
    @Results({
        @Result(property = "id", column = "userId"),
        @Result(property = "name", column = "userName"),
        @Result(property = "email", column = "userEmail"),
        @Result(property = "address.street", column = "addressStreet"),
        @Result(property = "address.city", column = "addressCity"),
        @Result(property = "address.country", column = "addressCountry")
    })
    MyBatisUser findByIdWithAddress(Long id);
}
